package com.znsd.zl.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * <p>
 *   Mybatis-plus 基本条件构造器生成工具类
 * <p/>
 * @ClassName GenerateQueryWrapper
 * @Description 生成mybatis-plus QueryWrapper条件查询构造器
 * @Author jaypdd
 * @Date 2020/8/19 23:08
 * @Version v1.0
 */
@Slf4j
public class GenerateQueryWrapper {

	/**
	 * 封装查询条件构造器QueryWrapper示例，封装了基本通用查询条件
	 * @param searchObject   条件对象
	 * @param paramMap       请求参数Map
	 * @return
	 */
	public static <T> QueryWrapper<T> initQueryWrapper(T searchObject, Map<String, String[]> paramMap) throws InvocationTargetException, IllegalAccessException {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
		if ( searchObject == null ) {
			return queryWrapper;
		}
		packagingPlusQueryWrapper(queryWrapper, searchObject, paramMap);
		log.info("【QueryWrapper条件构造器】，生成成功，查询条件：{}", searchObject.toString());
		return queryWrapper;
	}

	/**
	 * 初始化查询条件
	 * @param queryWrapper  封装的条件构造器
	 * @param searchObject  查询的条件实体类，根据该实体类进行表中列的通用查询条件
	 * @param paramMap      请求参数条件
	 */
	public static void packagingPlusQueryWrapper(QueryWrapper<?> queryWrapper, Object searchObject, Map<String, String[]> paramMap) throws InvocationTargetException, IllegalAccessException {
		if (searchObject == null) {
			return;
		}
		// 内省条件实体类所有属性
		PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(searchObject);
		// 条件构造器组装
		for (PropertyDescriptor bean : propertyDescriptors) {
			// 过滤空值，与class属性
			String name = bean.getName();
			Object value = bean.getReadMethod().invoke(searchObject);
			if ( value == null || "class".equals(name) ) {
				continue;
			}
			String column = attributeToColumn(name);
			// 日期区间查询
			if ( name.endsWith("Time") ) {
				String startValue = paramMap.get("startTime")[0].trim();
				String endValue = paramMap.get("endTime")[0].trim();
				queryWrapper.between(column, startValue, endValue);
				continue;
			}
			// 整数默认eq匹配
			System.out.println( bean.getPropertyType() );
			if ( value instanceof Integer ) {
				queryWrapper.eq(column, value);
			}else {
				// 字符默认右模糊
				queryWrapper.likeRight(column, value);
			}
		}
	}

	/**
	 * 驼峰属性字段转换数据库列名
	 * @param attributeName 属性名
	 * @return  返回该属性对应列名
	 */
	public static String attributeToColumn(String attributeName) {
		StringBuilder column = new StringBuilder();
		char[] chars = attributeName.toCharArray();
		for (char c : chars) {
			if ( Character.isUpperCase(c) ) {
				column.append("_" + c).toString().toLowerCase();
				continue;
			}
			column.append(c);
		}
		return column.toString();
	}
}
